// 用户状态管理
import { defineStore } from 'pinia';
import request from '../../utils/request';
import { ElMessage } from 'element-plus';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.userInfo.role === 'admin'
  },
  
  actions: {
    // 用户登录
    async login(loginData) {
      try {
        // 调用后端登录API
        const response = await request.post('/auth/login', {
          phone: loginData.phone,
          password: loginData.password
        });

        if (response.success) {
          const { token, user } = response.data;

          // 设置用户信息
          const userInfo = {
            id: user.id,
            username: user.username,
            real_name: user.real_name || user.realName || '',
            email: user.email || '',
            phone: user.phone,
            role: user.role,
            avatar: user.avatar || '',
            status: user.status || 'active'
          };

          this.token = token;
          this.userInfo = userInfo;

          // 存储到本地
          localStorage.setItem('token', token);
          localStorage.setItem('userInfo', JSON.stringify(userInfo));

          ElMessage.success(`欢迎回来，${user.real_name || user.realName || user.username}！`);
          return true;
        } else {
          ElMessage.error(response.message || '登录失败');
          return false;
        }
      } catch (error) {
        console.error('登录失败:', error);
        // 如果是网络错误或服务器错误，显示具体错误信息
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message);
        } else {
          ElMessage.error('登录失败，请稍后重试');
        }
        return false;
      }
    },
    
    // 用户注册
    async register(registerData) {
      try {
        // 调用后端注册API
        const response = await request.post('/auth/register', {
          username: registerData.username,
          email: registerData.email,
          phone: registerData.phone,
          password: registerData.password
        });

        if (response.success) {
          const { token, user } = response.data;

          // 设置用户信息
          const userInfo = {
            id: user.id,
            username: user.username,
            real_name: user.real_name || user.realName || '',
            email: user.email || '',
            phone: user.phone,
            role: user.role,
            avatar: user.avatar || '',
            status: user.status || 'active'
          };

          this.token = token;
          this.userInfo = userInfo;

          // 存储到本地
          localStorage.setItem('token', token);
          localStorage.setItem('userInfo', JSON.stringify(userInfo));

          ElMessage.success('注册成功！');
          return true;
        } else {
          ElMessage.error(response.message || '注册失败');
          return false;
        }
      } catch (error) {
        console.error('注册失败:', error);
        // 如果是网络错误或服务器错误，显示具体错误信息
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message);
        } else {
          ElMessage.error('注册失败，请稍后重试');
        }
        return false;
      }
    },

    // 直接设置登录状态（用于注册成功后）
    setLoginState(userInfo, token) {
      this.userInfo = userInfo;
      this.token = token;

      // 存储到本地
      localStorage.setItem('token', token);
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const res = await request.get('/auth/me');

        if (res.success) {
          const user = res.data.user;
          const userInfo = {
            id: user.id,
            username: user.username,
            real_name: user.real_name || user.realName || '',
            email: user.email || '',
            phone: user.phone,
            role: user.role,
            avatar: user.avatar || '',
            status: user.status || 'active'
          };

          this.userInfo = userInfo;
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          return userInfo;
        }

        return null;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        return null;
      }
    },
    
    // 用户登出
    logout() {
      this.token = '';
      this.userInfo = {};
      
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      
      ElMessage.success('已退出登录');
    }
  }
}); 